<?php
/**
 * Created by 绵阳市碳素云信息技术有限责任公司.
 * User: castle
 * Date: 2015/07/20
 * Time: 15:15
 */
	session_id('fwioafowfoawjfeaowjfeioa');
	session_start();
	$_SESSION['Server'] = false;
	$GLOBALS['ws'] = new swoole_websocket_server('0.0.0.0', 46030);
	$Server = new swoole_client(SWOOLE_SOCK_TCP,SWOOLE_SOCK_ASYNC);
	$Server->on('connect',function($cli){
		$_SESSION['Server'] = true;
		echo 'Connect to Server Success';
	});
	$Server ->on('receive',function($cli,$data){
		$data = unjson_encode($data);
		switch($data[0]){
			case 'm':
				//消息转发
				foreach($data[1] as $fd){
					$GLOBALS['ws']->push($fd,$data[2]);
				}
				break;
		}
	});

	$Server->on('close',function($cli){
		echo 'Close to Server Success';
	});

	$Server->on('error',function($cli){
		echo 'Error to Server Success';
	});

	$Server->connect('127.0.0.1',46031,1,1);
	$GLOBALS['Server'] = &$Server;
	function server ($data){
//		$Server = $GLOBALS['Server'];
//		include 'server.php';
	}

	$GLOBALS['ws']->set([
//		'heartbeat_check_interval' => 5, //每隔多少秒检测一次，单位秒，Swoole会轮询所有TCP连接，将超过心跳时间的连接关闭掉
//		'heartbeat_idle_time' => 600, //TCP连接的最大闲置时间，单位s , 如果某fd最后一次发包距离现在的时间超过
		//				'daemonize' => 1, //自动进入守护进程
		//				'log_file' => 'swoole.log'
	]);

	$GLOBALS['ws']->on('open', function ($ws, $request) {
		$data = json_encode(['n',$request->fd,$request->server['remote_addr']],JSON_UNESCAPED_UNICODE);
		server($data);
	});

	$GLOBALS['ws']->on('message', function ($ws, $frame) {
		echo "Message: {$frame->data}\n";
		$data = json_encode(['m',$frame->fd,$frame->data],JSON_UNESCAPED_UNICODE);
		server($data);
	});

	$GLOBALS['ws']->on('close', function ($ws, $fd) {
		$data = json_encode(['c',$fd],JSON_UNESCAPED_UNICODE);
		server($data);
	});

	$GLOBALS['ws']->start();